<?php

/**
 * 自动生成Service
 */

namespace Common\Service;

use Common\Service\SysFuncOperationService;

class SysFuncService {

  private static $instance;

  var $status = array(
    0 => '禁用' ,
    1 => '启用',
  );
  public static function instance() {
    if (self::$instance == null) {
      $instance = new SysFuncService ();
    }
    return $instance;
  }

  function get_default_row() {
    return array(
      'pid' => 0 ,
      'sort' => 99 ,
      'sys_type' => 2 ,
      'name' => '',
      'desc' => '',
      'is_menu' => 1 ,
      'status'=> 1 ,
      'url' => '',
      'create_time' => date('Y-m-d H:i:s'),
      'update_time' => date('Y-m-d H:i:s'),
    );
  }
  
  function get_by_id( $id ) {
    $SysFunc = M('SysFunc');
    $data = $SysFunc->find( $id );
    return $data ? $data : array();
  }
  
  function get_all_with_opertation() {
    
  }

  function get_by_cond( $config = array() ) {
    $default = array(
      'pid'      => 0,
      'sys_type' => 0 ,
      'is_menu'  => 0 ,
      'status'   => 0,
      'opertation' => FALSE , //是否带所有操作
    );
    $config = extend($config, $default);

    $where = array();
    if (!empty($config['status'])) {
      $where['sf.status'] = $config['status'];
    }
    
    if (!empty($config['is_menu'])) {
      $where['sf.is_menu'] = $config['is_menu'];
    }
    
    if ( !empty($config['sys_type']) ) {
      $where['sf.sys_type'] = $config['sys_type'];
    }

    $SysFunc = M('SysFunc');
    $order = ' sf.level ASC , sf.sort ASC ';
    $sql = '( SELECT  GROUP_CONCAT( sfo.NAME SEPARATOR  "，" ) FROM sys_func_operation sfo WHERE sfo.`func_id` = sf.`id` order by sort ) AS  operation' ;
    $data = $SysFunc
      ->field('sf.*, sd.text as sys_type_text , ' . $sql )
      ->alias('sf')
      ->join('sys_Dictionary sd on sd.id = sf.sys_type' , 'left')
      ->where($where)->order($order)->select();

    if ( $config['opertation'] ) {
      $SysFuncOperation = SysFuncOperationService::instance();
      foreach ( $data as $key => $row ) {
        $data[$key]['opertation'] = $SysFuncOperation->get_by_func_id( $row['id'] );
      }
    }
    
    $result = array();
    $index = array();

    foreach ( $data as $row ) {
      if ( $row['pid'] == $config['pid'] ) {  
        $result[$row['id']] = $row;
        $index[$row['id']] = & $result[$row['id']];
      } else {
        $index[$row['pid']]['son'][$row['id']] = $row;
        $index[$row['id']] = & $index[$row['pid']]['son'][$row['id']];
      }
    }
    
    return $this->_tree_to_array($result);
  }
  
  function get_level( $pid ) {
    if ( empty( $pid ) ) {
      return 1 ;
    }
    $data = $this->get_by_id($pid);
    if ( empty( $data ) ) {
      return 1 ;
    }
    return $data['level'] + 1 ;
  }

  function create($data) {
    $SysFunc = M('SysFunc');
    $ret = $SysFunc->add($data);
    if ($ret) {
      $SysFuncOperation = SysFuncOperationService::instance() ;
      $SysFuncOperation->add_default_opteration_by_func_id($ret);
      return ajax_arr('添加成功', TRUE, array(
        'id' => $ret
      ));
    } else {
      return ajax_arr('添加失败', FALSE);
    }
  }

  function update($id, $data) {
    $SysFunc = M('SysFunc');

    $ret = $SysFunc->where("id = %d", $id)->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    //先删除permission
    $SysRolePermission = SysRolePermissionService::instance();
    $SysRolePermission->delete_by_func($ids);
    
    //再删除操作
    $SysFuncOperation = SysFuncOperationService::instance() ;
    $func_opt_ret = $SysFuncOperation->del_by_func_id($ids);
    if ( $func_opt_ret  ) {
      $SysFunc = M('SysFunc');
      $ret = $SysFunc->delete($ids);
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    } else {
      return ajax_arr('删除失败', FALSE);
    }
  }

  function _tree_to_array($arr) {
    $ret = array();
    foreach ($arr as $val) {
      if (isset($val['son'])) {
        $val['son'] = $this->_tree_to_array($val['son']);
      }
      $ret[] = $val;
    }
    return $ret;
  }
  
  function get_main_menu( $sys_type = 2 ) {
    $SysFunc = M('SysFunc');
    $data = $SysFunc->field('id , name')->where('pid = 0 and sys_type = %d' , $sys_type )->order('sort')->select();  
    return $data ? $data : array();
  }

  function get_menu_by_roles( $roles_id , $sys_type = 2 ) {
    $roles_id_arr = implode(',', $roles_id);
    if ( $roles_id == 1 || in_array( 1, $roles_id_arr) ) {
      //是系统管理员
      return $this->get_by_cond(array(
        'is_menu' => 1 ,
        'status' => 1 ,
        'sys_type' => $sys_type ,
      ));
    } else {
      return $this->_get_menu_by_roles( $roles_id , $sys_type );
    }
  }
  
  function _get_menu_by_roles( $roles_id , $sys_type = 2 ) {
    $SysFunc = M('SysFunc');
    $field = 'DISTINCT sf.id , sf.pid , sf.name , sf.icon , sf.url , sf.level';
    $where = array(
      'sf.is_menu' => 1 ,
      'sf.status' => 1 ,
      'sf.sys_type' => $sys_type ,
      'srp.role_id' => array('exp' , " in ( $roles_id )"),
      'sfo.name' => '查看'
    );
    
    $data = $SysFunc
              ->alias('sf')
              ->field($field)
              ->join('sys_func_operation sfo on sfo.func_id = sf.id')
              ->join('sys_role_permission srp ON srp.opt_id = sfo.id')
              ->where( $where )
              ->order( 'sf.level ASC , sf.sort ASC' )
              ->select();
    //echo $SysFunc->_sql();
    $result = array();
    $index = array();

    foreach ( $data as $row ) {
      if ( $row['pid'] == 0 ) {  
        $result[$row['id']] = $row;
        $index[$row['id']] = & $result[$row['id']];
      } else {
        $index[$row['pid']]['son'][$row['id']] = $row;
        $index[$row['id']] = & $index[$row['pid']]['son'][$row['id']];
      }
    }
    
    return $this->_tree_to_array($result); 
  }
  
  /**
   * 根据角色取微信功能表
   * @param type $role_id
   * @return type
   */
  function get_wx_func_by_role( $role_id ) {
    $where = array(
      'sys_func.pid' => 33 ,
      'sys_func.is_func' => 1 ,
      'sys_func_operation.name' => '查看',
      'sys_role_permission.role_id' => array('in' , $role_id ),
    );
    $SysFunc = M('SysFunc');
    $data = $SysFunc
      ->field( ' sys_func.* ' )
      ->join('sys_func_operation ON sys_func_operation.func_id = sys_func.id')
      ->join('sys_role_permission ON sys_role_permission.opt_id = sys_func_operation.id')
      ->where($where)
      ->order('sys_func.sort')
      ->select();
    
    return $data ? $data : array();
    
  }
}
